package com.servlet.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig(location = "F:\\kaifamiao.1\\JavaWeb\\temp\\upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //处理文件上传逻辑，得到part对象
        Part file = req.getPart("file");
        //获取上传文件
        String fileName = file.getSubmittedFileName();
        System.out.println("上传的文件名称：" + fileName);
        // 获取上传的时候定义的name属性的值 file
        System.out.println("name:" + file.getName());
        fileName =File.separator + fileName;
        File file1 = new File(fileName);
        if (!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        System.out.println(fileName);
        try {
            file.write(fileName);
            resp.getWriter().write("<h3>上传成功</h3>");
        } catch (IOException e) {
            e.printStackTrace();
            resp.getWriter().write("<h3>上传失败</h3>");
        }
    }
}
